package com.danchuang.consumer.service;

import com.danchuang.consumer.dto.Order;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;

/**
 * @author haitao
 * @date 2021/7/26 10:26 上午
 */
@Service
@Slf4j
public class RabbitReceiver {
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "queue-1", durable = "true"),
            exchange = @Exchange(value = "exchange-1", type = "topic", ignoreDeclarationExceptions = "true"),
            key = "springboot.*"))
    @RabbitHandler
    public void onQueue1Message(Message message, Channel channel) throws Exception {
        System.out.println("queue-1接受消息：" + new String(message.getBody()));
        //获取消息标签
        long deliverTag = (long) message.getMessageProperties().getHeaders().get(AmqpHeaders.DELIVERY_TAG);
        //手动ack，不批量
        channel.basicAck(deliverTag, false);
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "${mqBindings.order.queue.value}", durable = "${mqBindings.order.queue.durable}"),
            exchange = @Exchange(value = "${mqBindings.order.exchange.value}", type = "${mqBindings.order.exchange.type}",
                    ignoreDeclarationExceptions = "${mqBindings.order.exchange.ignoreDeclarationExceptions}"), key = "${mqBindings.order.key}"))
    @RabbitHandler
    public void onOrderMessage(@Payload Order order, Channel channel, @Headers Map<String, Object> headers) {
        System.out.println("queue-2接受消息：" + order);
        //获取消息标签
        long deliverTag = (long) headers.get(AmqpHeaders.DELIVERY_TAG);
        //手动ack，不批量
        try {
            channel.basicAck(deliverTag, false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
